<template>
  <div class="app-container">
    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
      <div class="filter-container">
        <el-input
          v-model="listQuery.username"
          size="small"
          placeholder="用户名"
          style="width: 200px;margin-left:2%"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.nickname"
          size="small"
          placeholder="昵称"
          style="width: 200px;margin-left:2%"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <treeselect
          v-model="deptId"
          :options="depts"
          style="width: 300px;float:left;margin-top:0px;"
          placeholder="选择部门"
        />
        <p style="display:inline-block;margin-left:2%">状态：</p>
        <el-select
          v-model="listQuery.type"
          size="small"
          placeholder="全部"
          clearable
          class="filter-item"
          style="width: 130px"
        >
          <el-option
            v-for="item in calendarTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
        <el-button
          class="filter-item"
          type="success"
          icon="el-icon-search"
          size="small"
          @click="handleFilter"
        >搜索</el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleCreate"
        >添加</el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :key="tableKey"
        :data="list"
        size="small"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column
          :class-name="getSortClass('id')"
          label="ID"
          prop="id"
          sortable="custom"
          align="center"
          width="80"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" min-width="200px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" width="250px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.nickname }}</span>
            <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column label="手机号" width="250px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.reviewer }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="175" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.emailyear }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" width="175" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deptName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="150px">
          <template slot-scope="{ row }">
            <span>
              {{
              row.status == 0
              ? "无效"
              : row.status == 1
              ? "正常"
              : row.status == 2
              ? "锁定"
              : "暂无"
              }}
            </span>
            <!-- <span v-else>0</span> -->
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="260"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{ row }">
            <el-button size="small" align="center" type="primary" @click="handleUpdate(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.start"
        :limit.sync="listQuery.length"
        @pagination="getList"
      />

      <el-dialog
        :close-on-click-modal="false"
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        append-to-body
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="150px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="用户名/登录名">
            <el-input v-model="temp.username" />
          </el-form-item>
          <el-form-item v-if="dialogStatus == 'create'" label="密码">
            <el-input v-model="temp.password" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="temp.nickname" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="temp.phone" />
          </el-form-item>
          <el-form-item style="width:800px" label="地址">
            <v-distpicker
              :province="temp.province"
              :city="temp.city"
              :area="temp.county"
              @selected="select"
            />
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input v-model="temp.address" />
          </el-form-item>
          <el-form-item label="部门">
            <treeselect v-model="deptId" :options="depts" style="width: 370px;" placeholder="选择部门" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
              <el-option
                v-for="item in calendarTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-checkbox-group v-model="ckRoles">
              <el-checkbox
                v-for="(item, index) in getRoles"
                :label="item.id"
                :key="index"
              >{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >确定</el-button>
        </div>
      </el-dialog>
    </el-col>
  </div>
</template>

<script>
import { userMananeList, createArticle, updateArticle } from "@/api/article";
import { getAll, getLevel } from "@/api/role";
import { parseTime } from "@/utils";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getDepts } from "@/api/dept";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
// const cityOptions = ['ADMIN', '县域经理', '乡镇协理'];

const calendarTypeOptions = [
  { key: 0, display_name: "无效" },
  { key: 1, display_name: "正常" },
  { key: 2, display_name: "锁定" }
];
const sexTypeOptions = [
  { key: 0, display_name: "女" },
  { key: 1, display_name: "男" }
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});
const calendarSexKeyValue = sexTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});
export default {
  inject: ["reload"],
  name: "ComplexTable",
  components: { Pagination, Treeselect },
  // directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
    sexFliter(type) {
      return calendarSexKeyValue[type];
    }
  },
  data() {
    return {
      // checkedCities: temp.
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      ckRoles: [],
      deptId: null,
      deptno: null,
      depts: [],
      deptArr: {},
      listQuery: {
        start: 1,
        length: 10,
        username: "",
        nickname: "",
        sort: "+id",
        type: "",
        roleIds: [],
        id: 0,
        password: ""
      },
      // importanceOptions: [1, 2, 3],
      getRoles: [],
      calendarTypeOptions,
      sexTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" }
      ],
      showReviewer: false,
      temp: {
        id: undefined,
        // status: 'published'
        password: "",
        roleIds: "",
        provinceCode: "",
        cityCode: "",
        countyCode: "",
        province: "",
        city: "",
        county: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create"
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" }
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change"
          }
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" }
        ]
      },
      downloadLoading: false
    };
  },
  created() {
    this.getList();
    this.getDepts();
    this.getAllUser();
  },
  methods: {
    select: function(data) {
      this.temp.provinceCode = data.province.code;
      this.temp.cityCode = data.city.code;
      this.temp.countyCode = data.area.code;
      this.temp.province = data.province.value;
      this.temp.city = data.city.value;
      this.temp.county = data.area.value;
    },

    // 获取部门
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.data.content;
      });
    },
    // 获取角色
    getAllUser() {
      getAll().then(res => {
        this.getRoles = res.data;
      });
    },
    getList() {
      this.listLoading = true;
      console.log(this.listQuery.start);
      var params = {
        pageConvert: true,
        start: this.listQuery.start - 1,
        length: this.listQuery.length,
        username: this.listQuery.username,
        nickname: this.listQuery.nickname,
        status: this.listQuery.type,
        id: this.listQuery.id,
        deptId: this.deptId
      };
      // console.log(params.roleIds)
      userMananeList(params).then(response => {
        this.list = response.data.content;
        this.total = response.data.totalElements;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.start = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },

    // 重置数据
    resetTemp() {
      this.temp = {
        id: undefined,
        password: "",
        deptId: ""
      };
      this.ckRoles = [];
    },
    handleCreate() {
      // this.getAllUser()
      // this.getDepts()
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          // this.temp.password = this.listQuery.password
          this.temp.deptId = this.deptId;
          this.temp.roleIds = this.ckRoles;
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000
            });
          });
          this.reload();
        }
      });
    },

    // 编辑弹窗
    handleUpdate(row) {
      this.resetTemp();
      this.listQuery.id = row.id;
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      getLevel(row.id).then(res => {
        res.data.forEach(item => {
          // this.ckRoles = []
          this.ckRoles.push(item.id.roleId);
        });
      });
      this.deptId = row.deptId;
      console.log(this.deptId);
      this.temp = Object.assign({}, row); // copy obj
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.roleIds = this.ckRoles;
          // this.temp.pid=
          this.temp.deptId = this.deptId;
          console.log(this.temp.deptId);
          const tempData = Object.assign({}, this.temp);
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v);
                this.list.splice(index, 1, this.temp);
                break;
              }
            }
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000
              // tempData: ""
            });
          });
          // this.reload()
        }
      });
    },
    handleFetchPv(pv) {
      // fetchPv(pv).then(response => {
      //   this.pvData = response.data.pvData
      //   this.dialogPvVisible = true
      // })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}`
        ? "ascending"
        : sort === `-${key}`
        ? "descending"
        : "";
    }
  }
};
</script>
<style>
.el-input--small .el-input__inner {
  height: 36px !important;
}
</style>
